package hiresoft.ui;

import hiresoft.network.*;
import hiresoft.users.Admin;
import javax.swing.*;
import java.util.ArrayList;


/**
 * Creates the User Interface and
 *  functionality for the Admin account
 *
 * @author Kevin Carlino
 */
public class AdminFrame extends UserFrame {
    DefaultListModel model;
    ArrayList<Integer> accID;
    int doDelete;
    boolean createAccount;
    Network net;

    public AdminFrame(LoginFrame context, Admin _user){
        super(context, _user);
        initComponents();
    }

    /**
     * Sets the network/connection and calls the main function.
     */
    public void connect() {
        try {
            net = Network.getInstance();
            btnCancel.setEnabled(false);
            getAccs();
        }
        catch (Exception e) {
            JOptionPane.showMessageDialog(null, "No network connection established.");
        }
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtUsername = new javax.swing.JTextField();
        lblUsername = new javax.swing.JLabel();
        lblPassword = new javax.swing.JLabel();
        txtPassword = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        lblAccess = new javax.swing.JLabel();
        chkDelete = new javax.swing.JCheckBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstAccounts = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        lblID = new javax.swing.JLabel();
        btnAdd = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        accessBox = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        txtUsername.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtUsernameMouseClicked(evt);
            }
        });
        txtUsername.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtUsernameFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtUsernameFocusLost(evt);
            }
        });

        lblUsername.setText("Username");

        lblPassword.setText("Password");

        txtPassword.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtPasswordMouseClicked(evt);
            }
        });
        txtPassword.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtPasswordFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPasswordFocusLost(evt);
            }
        });

        jButton1.setText("Submit");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        lblAccess.setText("Access");

        chkDelete.setText("Delete Account?");
        chkDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkDeleteActionPerformed(evt);
            }
        });

        lstAccounts.setModel(new DefaultListModel());
        lstAccounts.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lstAccountsMouseClicked(evt);
            }
        });
        lstAccounts.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                lstAccountsValueChanged(evt);
            }
        });
        lstAccounts.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                lstAccountsKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                lstAccountsKeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(lstAccounts);

        jLabel1.setText("Account ID:");

        lblID.setText("0");

        btnAdd.setText("New Account");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        accessBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Set Access Level", "Applicant", "Recruiter", "Reviewer", "Admin" }));
        accessBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                accessBoxActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(btnAdd, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(lblID))
                    .addComponent(lblUsername)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(chkDelete))
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                    .addComponent(btnCancel, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(accessBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtUsername, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(lblPassword, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(txtPassword, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)
                        .addComponent(lblAccess, javax.swing.GroupLayout.Alignment.LEADING)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(lblID))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblUsername)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(21, 21, 21)
                        .addComponent(lblPassword)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblAccess)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(accessBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(chkDelete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void lstAccountsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstAccountsMouseClicked
}//GEN-LAST:event_lstAccountsMouseClicked

    private void lstAccountsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_lstAccountsKeyPressed

}//GEN-LAST:event_lstAccountsKeyPressed

    private void lstAccountsKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_lstAccountsKeyReleased
        if(lstAccounts.isEnabled())
            getAcc();
}//GEN-LAST:event_lstAccountsKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        int selAccID = lstAccounts.getSelectedIndex();

        if(accessBox.getSelectedIndex() < 1)
            accessBox.setSelectedIndex(1);
        else if(accessBox.getSelectedIndex() > 4)
            accessBox.setSelectedIndex(4);

        int access = accessBox.getSelectedIndex();

        if(selAccID > -1) {
            if(doDelete == 0) {
                try {
                        net.out.Insert(Integer.parseInt(lblID.getText()));
                        net.out.Insert(txtUsername.getText());
                        net.out.Insert(txtPassword.getText());
                        if (access == 4)
                            access = 5;
                        net.out.Insert(access);
                        net.out.Send(Packets.P_EDITACCOUNT);

                        if (net.Ready())
                        {
                            if (net.in.getPacketId() == Packets.P_EDITACCOUNT)
                            {
                                if(net.in.getDWord() != 0)
                                {
                                    int newID = net.in.getDWord();
                                    accID.add(newID);
                                    JOptionPane.showMessageDialog(null, "The account has been edited successfully.");
                                }
                                else
                                    JOptionPane.showMessageDialog(null, "Failed to edit account.");
                            }
                        }
                    }
                    catch (Exception e) {
                        JOptionPane.showMessageDialog(null, "Error: " + e);
                    }
            }
            else {
                try {
                        net.out.Insert(Integer.parseInt(lblID.getText()));
                        net.out.Insert(accessBox.getSelectedIndex());
                        net.out.Send(Packets.P_DELETEACCOUNT);

                        if (net.Ready())
                        {
                            if (net.in.getPacketId() == Packets.P_DELETEACCOUNT)
                            {
                                if(net.in.getDWord() != 0)
                                {
                                    JOptionPane.showMessageDialog(null, "The account has been deleted successfully.");
                                }
                                else
                                    JOptionPane.showMessageDialog(null, "Failed to delete account.");
                            }
                        }
                    }
                    catch (Exception e) {
                        JOptionPane.showMessageDialog(null, "Error: " + e);
                    }
            }
        }
        else {
            JOptionPane.showMessageDialog(null, "You do not have an account selected.");
        }
        if(createAccount) {
            lstAccounts.setEnabled(true);
            btnAdd.setEnabled(true);
            chkDelete.setEnabled(true);
            btnCancel.setEnabled(false);
        }
        if(doDelete == 1) {
            doDelete = 0;
            chkDelete.setSelected(false);
            txtUsername.setEnabled(true);
            txtUsername.setText("");
            txtPassword.setEnabled(true);
            txtPassword.setText("");
            accessBox.setEnabled(true);
            accessBox.setSelectedIndex(0);
            lblID.setText("0");
        }
        model.clear();
        getAccs();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void chkDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkDeleteActionPerformed
        if(doDelete == 1) {
            doDelete = 0;
            txtUsername.setEnabled(true);
            txtPassword.setEnabled(true);
            accessBox.setEnabled(true);
        }
        else {
            doDelete = 1;
            txtUsername.setEnabled(false);
            txtPassword.setEnabled(false);
            accessBox.setEnabled(false);
        }
    }//GEN-LAST:event_chkDeleteActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        model = ((DefaultListModel)lstAccounts.getModel());
        createAccount = true;

        model.addElement("New Account");
        lstAccounts.setEnabled(false);
        btnAdd.setEnabled(false);
        lstAccounts.setSelectedIndex(model.size() - 1);
        txtUsername.setText("Enter Username");
        txtPassword.setText("Enter Password");
        accessBox.setSelectedIndex(0);
        lblID.setText("0");
        chkDelete.setEnabled(false);
        btnCancel.setEnabled(true);
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        model = ((DefaultListModel)lstAccounts.getModel());
        createAccount = true;

        model.removeElement("New Account");
        lstAccounts.setEnabled(true);
        btnAdd.setEnabled(true);
        lstAccounts.setSelectedIndex(model.size() - 1);
        txtUsername.setText("");
        txtPassword.setText("");
        accessBox.setSelectedIndex(0);
        lblID.setText("0");
        chkDelete.setEnabled(true);
        btnCancel.setEnabled(false);
    }//GEN-LAST:event_btnCancelActionPerformed

    private void accessBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_accessBoxActionPerformed
        
    }//GEN-LAST:event_accessBoxActionPerformed

    private void lstAccountsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstAccountsValueChanged
        if(lstAccounts.isEnabled() && lstAccounts.getValueIsAdjusting())
            getAcc();
    }//GEN-LAST:event_lstAccountsValueChanged

    private void txtUsernameMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtUsernameMouseClicked

    }//GEN-LAST:event_txtUsernameMouseClicked

    private void txtPasswordMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtPasswordMouseClicked

    }//GEN-LAST:event_txtPasswordMouseClicked

    private void txtUsernameFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtUsernameFocusGained
        // TODO add your handling code here:
        if(txtUsername.getText().equals("Enter Username")){
            txtUsername.setText(null);
        }
    }//GEN-LAST:event_txtUsernameFocusGained

    private void txtPasswordFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPasswordFocusGained
        // TODO add your handling code here:
        if(txtPassword.getText().equals("Enter Password")){
            txtPassword.setText(null);
        }
    }//GEN-LAST:event_txtPasswordFocusGained

    private void txtUsernameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtUsernameFocusLost
        if(txtUsername.getText().isEmpty()){
            txtUsername.setText("Enter Username");
        }
    }//GEN-LAST:event_txtUsernameFocusLost

    private void txtPasswordFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPasswordFocusLost
        if(txtPassword.getText().isEmpty()){
            txtPassword.setText("Enter Password");
        }
    }//GEN-LAST:event_txtPasswordFocusLost

    /**
     * Retrieves a list of all accounts in the database and displays them.
     */
    public void getAccs() {
        model = ((DefaultListModel)lstAccounts.getModel());

        try {
            net.out.Send(Packets.P_GETACCOUNTS);
            if (net.Ready())
            {
                if (net.in.getPacketId() == Packets.P_GETACCOUNTS)
                {
                        if(net.in.getDWord() != 0)
                        {
                            int accNums = net.in.getDWord();
                            accID = new ArrayList<Integer>();

                            for(int i = 0; i < accNums; i++)
                            {
                                accID.add(net.in.getDWord());
                                model.add(i, net.in.getString());
                            }
                        }
                        else
                            JOptionPane.showMessageDialog(null, "Failed to retrieve account listing.");
                }
            }
        }
        catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error: " + e);
        }
    }

    /**
     * Retrieves specific account information and displays it.
     */
    public void getAcc() {
       int selAccID = lstAccounts.getSelectedIndex();

        try {
            net.out.Insert(accID.get(selAccID));
            net.out.Send(Packets.P_GETACCOUNT);
            if (net.Ready())
            {
                if (net.in.getPacketId() == Packets.P_GETACCOUNT)
                {
                    if(net.in.getDWord() != 0)
                    {
                        String username = net.in.getString();
                        String password = net.in.getString();
                        int access = net.in.getDWord();

                        txtUsername.setText(username);
                        txtPassword.setText(password);
                        if (access == 5)
                            access = 4;
                        accessBox.setSelectedIndex(access);
                        lblID.setText(String.valueOf(accID.get(selAccID)));
                    }
                    else
                        JOptionPane.showMessageDialog(null, "Failed to retrieve account information.");
                }
            }
        }
        catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error: " + e);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox accessBox;
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnCancel;
    private javax.swing.JCheckBox chkDelete;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblAccess;
    private javax.swing.JLabel lblID;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblUsername;
    private javax.swing.JList lstAccounts;
    private javax.swing.JTextField txtPassword;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables

}